<script setup lang="ts">

import {UploadFilled} from "@element-plus/icons-vue";
import {getFile, removeFile} from "@/api/fileApi.js";
import {ElMessage} from "element-plus";
import * as XLSX from 'xlsx'
import {useUserStore} from "@/pinia/stores/user";
const userStore = useUserStore()
const userData = userStore.userInfo
const dialogFormVisibles = ref(false);
const emit = defineEmits(['submitAdds', 'close', 'update:modelValue'])
const fileList = ref([]);
const formData = ref([])
const props = defineProps({
  batchAddVisible: {
    default: {}
  }
})
const uploadFile = (val) => {
}
const handleAvatarSuccess = () => {
}
const RemoveFile = async (uploadFile, uploadFiles) => {

}

const handChange = async (file) => {
  const fileReader = new FileReader();
  fileReader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const wsname = workbook.SheetNames[0]; // 取第一张表
      const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成 JSON 格式的表格内容
      formData.value = ws;
    } catch (e) {
      console.error(e);
      return false;
    }
  };
  fileReader.readAsArrayBuffer(file.raw);
}

const FileDownload = async () => {
  let fileName = props.batchAddVisible.fileName;
  console.log(fileName, "fileName")
  await getFile(fileName).then(res => {
    let fileUrl = 'http://localhost:8082/static/img/real/' + fileName;
    let extName = fileUrl.substring(fileUrl.lastIndexOf("."));
    const link = document.createElement('a');
    link.download =  props.batchAddVisible.fileName + extName;
    link.href = fileUrl
    link.target = "_blank";
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
    ElMessage.success("下载成功");
  }).catch(res => {
    ElMessage.error(res.data.message)
  });
}
const submitAdds =  () => {
  if (fileList.value.length === 0){
    ElMessage.error("请选择文件");
    return;
  }
  emit('submitAdds', formData.value, userData.username)
  dialogFormVisibles.value = false;
  fileList.value = [];
  formData.value = [];
}
const handleClose = () => {
  props.batchAddVisible.dialogFormVisibles = false;
}
</script>

<template>
  <el-dialog v-model="batchAddVisible.dialogFormVisibles" center title="批量添加" width="500">
    <el-upload v-model:file-list="fileList"
               class="upload-demo"
               drag
               :http-request="uploadFile"
               limit="1"
               accept=".xlsx"
               multiple
               :on-progress="handleAvatarSuccess"
               :on-remove="RemoveFile"
               :on-change="handChange">
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        选择Excel文件或 <em>拖拽上传</em>
      </div>
    </el-upload>
    <el-form-item>
      <div style="align-items: center">{{batchAddVisible.fileName}}</div>
      <el-button @click="FileDownload" size="small" plain type="warning" style="margin-left: 5px;margin-top: 3px">点击下载</el-button>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitAdds">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
